<?php

namespace app\admin\service;

use app\admin\dao\ConsultingServerDao;
use app\admin\model\UM as UM;
use app\common\model\ConsultingServer;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class ConsultingServerService
 * @package app\chat\service
 */
class ConsultingServerService
{
    private ConsultingServerDao $consultingServerDao;

    public function __construct(ConsultingServerDao $consultingServerDao)
    {
        $this->consultingServerDao = $consultingServerDao;
    }

    /**
     * 列表
     * @param \app\admin\model\UM|null $user
     * @param int|null $page
     * @param int|null $page_size
     * @return array
     */
    public function index(?UM $user, ?int $page = null, ?int $page_size = null): array
    {
        return $this->consultingServerDao->listServers($page, $page_size);
    }

    /**
     * 查询
     * @param \app\admin\model\UM|null $user
     * @param int $id
     * @return ConsultingServer
     */
    public function read(?UM $user, int $id): ?ConsultingServer
    {
        //这里如果要修改查询，建议把查询放到dao层去
        return $this->consultingServerDao->findByPK($id, true);
    }

    /**
     * 新增 自定义服务
     * @param \app\admin\model\UM $user
     * @param array $params
     * @return  \app\common\model\ConsultingServer
     */
    public function add(UM $user, array $params): ConsultingServer
    {
        $params['userId'] = $user->id;
        // 现在只能添加自定义服务
        $params['serverType'] = 1;
        // 现在只可以添加时长的，不可以添加次数的
        $params['isChatFreely'] = '1';
        // $params['chatFreelyDuration'] = '0';
        // 自定义服务都需要显示电话
        $params['isShowCallTel'] = '1';
        $params['showCallTelDuration'] = 24;
        $params['lawyerShareRate'] = 0.7;
        $params['inviterShareRate'] = 0.03;

        $params['dataIcon'] ??= null;
        if (is_blank($params['dataIcon'])) {
            $rand = mt_rand(1, 11);
            $params['dataIcon'] = "/storage/static/images/a2/t$rand.png";
        }

        $params['created'] = 0;

        $this->checkParams($params);

        $this->checkRepeat($params['name']);

        return $this->consultingServerDao->insertActive($params, []);
    }

    /**
     * 更新 自定义服务
     * @param \app\admin\model\UM $user
     * @param int $id
     * @param array $params
     * @return \app\common\model\ConsultingServer
     */
    public function modify(UM $user, int $id, array $params): ConsultingServer
    {
        $record = ConsultingServer::field(true)->where('id', $id)->where('serverType', '1')->find();

        if (is_null($record)) {
            throw new DataNotExistException('该自定义服务不存在或已被删除');
        }

        $this->checkParams($params);

        $this->checkRepeat($params['name'], $id);

        $allowField = ['icon', 'name', 'chatFreelyDuration', 'showPrice', 'price', 'desc1', 'desc2', 'desc3', 'ord'];
        $this->consultingServerDao->updateActive($record, $params, $allowField);

        return $record;
    }

    /**
     * 删除
     * @param \app\admin\model\UM $user
     * @param int $id
     */
    public function rm(UM $user, int $id): void
    {
        //这里如果要修改查询，建议把查询就放到这里
        $record = ConsultingServer::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            return;
        }

        $record->deleted = time();
        $record->save();
    }

    private function checkRepeat($name, $id = null): void
    {
        $record = ConsultingServer::where('name', $name)
            ->when(is_id($id), function ($query) use ($id) {
                $query->where('id', '<>', $id);
            })
            ->find();

        if (!is_null($record)) {
            throw new ValidateException('该服务名称已存在');
        }
    }

    /**
     * 检查参数
     * @param array $params
     * @return void
     */
    public function checkParams(array $params): void
    {
        if (is_blank($params['icon'] ?? null)) {
            throw new ValidateException('请上传图标');
        }

        if (is_blank($params['name'] ?? null)) {
            throw new ValidateException('请输入服务名称');
        }

        if (is_blank($params['showPrice'] ?? null)) {
            throw new ValidateException('请输入原价');
        }
        if (!is_numeric($params['showPrice']) || $params['showPrice'] <= 0) {
            throw new ValidateException('请输入正确的原价');
        }

        if (is_blank($params['price'] ?? null)) {
            throw new ValidateException('请输入现价');
        }
        if (!is_numeric($params['price']) || $params['price'] <= 0) {
            throw new ValidateException('请输入正确的现价');
        }

        if (is_blank($params['chatFreelyDuration'] ?? null)) {
            throw new ValidateException('请输入时长');
        }
        if (!is_numeric($params['chatFreelyDuration']) || $params['chatFreelyDuration'] < 0) {
            throw new ValidateException('请输入正确的时长');
        }
        if (isset($params['ord']) && !is_numeric($params['ord'])) {
            throw new ValidateException('请输入正确的排序');
        }
    }
}
